﻿using IrisMembership.DataLayer;
using IrisMembership.DomainClasses;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IrisMembership.ServiceLayer
{
    public class RoleService : IRoleService
    {
        private readonly IDbSet<Role> _roles;

        public RoleService(IIrisDbContext dbContext)
        {
            _roles = dbContext.Set<Role>();
        }

        public void AttachToContext(Role role)
        {
            _roles.Attach(role);
        }

        public IList<Role> GetRolesOfUser(int userId)
        {
            return _roles.Where(r => r.Users.Any(u => u.Id == userId)).Include(r => r.ChildrenRoles).ToList();
        }

        public async Task<IList<Role>> GetRolesOfUserAsync(int userId)
        {
            return await _roles.Where(r => r.Users.Any(u => u.Id == userId)).Include(r => r.ChildrenRoles).ToListAsync();
        }


        public void Add(Role role)
        {
            _roles.Add(role);
        }



        public IList<Role> GetRolesOfUserExceptMainRole(int userId)
        {
            return _roles.Where(r => r.ParentRole.Users.Any(u => u.Id == userId) || r.Name == IrisMemebrshipConfigurations.DefaultUserRole)
                .Include(r => r.ChildrenRoles)
                .ToList();
        }

        public async Task<IList<Role>> GetRolesOfUserExceptMainRoleAsync(int userId)
        {
            return await _roles.Where(r => r.ParentRole.Users.Any(u => u.Id == userId) || r.Name == IrisMemebrshipConfigurations.DefaultUserRole)
                .Include(r => r.ChildrenRoles)
                .ToListAsync();
        }


        public async Task<IList<Role>> GetUserRolesAsync(int userId)
        {
            return await _roles.Where(r => r.Users.Any(u => u.Id == userId)).Include(u => u.ChildrenRoles).ToListAsync();
        }



        public Role Find(int roleId)
        {
            return _roles.Find(roleId);
        }


        public IList<Role> GetUserRoles(int userId)
        {
            return _roles.Where(r => r.Users.Any(u => u.Id == userId)).Include(u => u.ChildrenRoles).ToList();
        }


        public IList<Role> GetUserRolesAndPermissions(int userId)
        {
            return _roles.Where(r => r.Users.Any(u => u.Id == userId)).Include(u => u.ChildrenRoles).Include(u => u.Permissions).ToList();
        }

        public async Task<IList<Role>> GetUserRolesAndPermissionsAsync(int userId)
        {
            return await _roles.Where(r => r.Users.Any(u => u.Id == userId)).Include(u => u.Permissions).ToListAsync();
        }
    }
}
